import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getUserInfo, updateUserInfo } from '@/api/user'
import { login, logout, refreshToken } from '@/api/auth'
import { storage } from '@/utils'
import router from '@/router'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(storage.get('token') || '')
  const refreshTokenValue = ref(storage.get('refreshToken') || '')
  const userInfo = ref(null)
  const permissions = ref([])
  const roles = ref([])
  const isLoggedIn = computed(() => !!token.value)
  const avatar = computed(() => userInfo.value?.avatar || '')
  const nickname = computed(() => userInfo.value?.nickname || userInfo.value?.username || '未登录')
  const email = computed(() => userInfo.value?.email || '')
  const phone = computed(() => userInfo.value?.phone || '')

  // 登录
  const loginAction = async (loginData) => {
    try {
      const response = await login(loginData)
      const { token: newToken, refreshToken: newRefreshToken, user } = response.data
      
      // 保存 token
      token.value = newToken
      refreshTokenValue.value = newRefreshToken
      storage.set('token', newToken)
      storage.set('refreshToken', newRefreshToken)
      
      // 保存用户信息
      userInfo.value = user
      permissions.value = user.permissions || []
      roles.value = user.roles || []
      
      return response
    } catch (error) {
      throw error
    }
  }

  // 退出登录
  const logoutAction = async () => {
    try {
      if (token.value) {
        await logout()
      }
    } catch (error) {
      console.error('退出登录失败:', error)
    } finally {
      // 清除本地数据
      token.value = ''
      refreshTokenValue.value = ''
      userInfo.value = null
      permissions.value = []
      roles.value = []
      storage.remove('token')
      storage.remove('refreshToken')
      
      // 跳转到登录页
      router.push('/login')
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      if (!token.value) {
        throw new Error('未登录')
      }
      
      const response = await getUserInfo()
      const user = response.data
      
      userInfo.value = user
      permissions.value = user.permissions || []
      roles.value = user.roles || []
      
      return user
    } catch (error) {
      // 如果获取用户信息失败，可能是 token 过期
      if (error.response?.status === 401) {
        await logoutAction()
      }
      throw error
    }
  }

  // 更新用户信息
  const updateUserInfoAction = async (data) => {
    try {
      const response = await updateUserInfo(data)
      const updatedUser = response.data
      
      // 更新本地用户信息
      userInfo.value = { ...userInfo.value, ...updatedUser }
      
      return response
    } catch (error) {
      throw error
    }
  }

  // 刷新 token
  const refreshTokenAction = async () => {
    try {
      if (!refreshTokenValue.value) {
        throw new Error('无刷新令牌')
      }
      
      const response = await refreshToken({
        refreshToken: refreshTokenValue.value
      })
      
      const { token: newToken, refreshToken: newRefreshToken } = response.data
      
      // 更新 token
      token.value = newToken
      refreshTokenValue.value = newRefreshToken
      storage.set('token', newToken)
      storage.set('refreshToken', newRefreshToken)
      
      return response
    } catch (error) {
      // 刷新失败，退出登录
      await logoutAction()
      throw error
    }
  }

  // 检查权限
  const hasPermission = (permission) => {
    if (!permission) return true
    return permissions.value.includes(permission)
  }

  // 检查角色
  const hasRole = (role) => {
    if (!role) return true
    return roles.value.includes(role)
  }

  // 检查多个权限（AND 关系）
  const hasAllPermissions = (permissionList) => {
    if (!permissionList || permissionList.length === 0) return true
    return permissionList.every(permission => permissions.value.includes(permission))
  }

  // 检查多个权限（OR 关系）
  const hasAnyPermission = (permissionList) => {
    if (!permissionList || permissionList.length === 0) return true
    return permissionList.some(permission => permissions.value.includes(permission))
  }

  // 检查多个角色（AND 关系）
  const hasAllRoles = (roleList) => {
    if (!roleList || roleList.length === 0) return true
    return roleList.every(role => roles.value.includes(role))
  }

  // 检查多个角色（OR 关系）
  const hasAnyRole = (roleList) => {
    if (!roleList || roleList.length === 0) return true
    return roleList.some(role => roles.value.includes(role))
  }

  // 初始化用户信息
  const initUserInfo = async () => {
    if (token.value && !userInfo.value) {
      try {
        await fetchUserInfo()
      } catch (error) {
        console.error('初始化用户信息失败:', error)
      }
    }
  }

  // 重置状态
  const resetState = () => {
    token.value = ''
    refreshTokenValue.value = ''
    userInfo.value = null
    permissions.value = []
    roles.value = []
    storage.remove('token')
    storage.remove('refreshToken')
  }

  return {
    // 状态
    token,
    refreshTokenValue,
    userInfo,
    permissions,
    roles,
    
    // 计算属性
    isLoggedIn,
    avatar,
    nickname,
    email,
    phone,
    
    // 方法
    loginAction,
    logoutAction,
    fetchUserInfo,
    updateUserInfoAction,
    refreshTokenAction,
    hasPermission,
    hasRole,
    hasAllPermissions,
    hasAnyPermission,
    hasAllRoles,
    hasAnyRole,
    initUserInfo,
    resetState
  }
}, {
  persist: {
    key: 'user-store',
    storage: localStorage,
    paths: ['token', 'refreshTokenValue', 'userInfo', 'permissions', 'roles']
  }
})